<template>
  <div ref="oScrollList" class="scroll-list">
    <van-pull-refresh class="refresh" v-model="refresh" @refresh="onRefresh">
      <div class="list" :style="{ minHeight: scrollListHeight }">
        <slot></slot>
        <div ref="oloadingWapper" class="loading-wapper" v-show="!refresh && !finished"></div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';

const props = defineProps({
  finished: { type: Boolean, default: false }
})

const emit = defineEmits(['refresh', 'load']);

//  编写上拉加载，下拉刷新功能
const refresh = ref(false);

const onRefresh = () => {
  setTimeout(() => {
    refresh.value = false;
    emit('refresh');  //  下拉刷新
  }, 300);
};

//  元素
const oScrollList = ref(null);
const oloadingWapper = ref(null);
//  记录当前容器的可视化高度， 保证在数据不足的时候也能够撑满容器
const scrollListHeight = ref('100%');
onMounted(() => {
  scrollListHeight.value = getComputedStyle(oScrollList.value, null)['height'];

  const ob = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        // 元素可见时的操作
        if (!props.finished) {
          emit('load');
        }
      }
    })
  }, {
    root: document.querySelector('.scroll-list'),
    threshold: .5
  });
  // console.log(document.querySelector('.loading-wapper'));
  ob.observe(oloadingWapper.value);
})
</script>

<style lang="scss" scoped>
:deep .van-pull-refresh__track {
  height: auto;
}

.scroll-list {
  flex: 1;
  overflow-y: auto;

  .refresh {
    min-height: 100%;
  }

  .list {
    display: flex;
    flex-direction: column;
  }

  .loading-wapper {
    height: .1rem;
  }
}
</style>